import { reactive } from "vue"; // 确保已导入reactive
import type { FormRules } from "element-plus";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";

/** 自定义表单规则校验 */
// 添加一个变量来存储表单的原始名称
let originalFormId = 0;
let tenantId = 0;
export function setOriginalFormId(id: number) {
  originalFormId = id;
}
export function setTenantId(id: number) {
  tenantId = id;
}

export const formRules = reactive(<FormRules>{
  name: [
    { required: true, message: "区域名称为必填项", trigger: "blur" },
    {
      validator: async (rule, value, callback) => {
        if (!value) {
          callback();
          return;
        }
        try {
          // 构建请求参数
          const params: { name: string; tenantId: number; excludeId?: number } =
            {
              name: value,
              tenantId: tenantId
            };

          // 只有当 originalFormId 不为 0 时才添加 excludedId 参数
          if (originalFormId !== 0) {
            params.excludeId = originalFormId;
          }

          // 发送请求检查分区名称是否存在/api/Zone/check-name-unique
          const res = await http.get(
            changeHttpLink("/api/Zone/check-name-unique"),
            { params }
          );
          // 添加类型断言以解决TypeScript类型检查问题
          const typedRes = res as {
            Success: boolean;
            Data?: boolean;
          };
          console.log(typedRes);
          // 修复条件判断逻辑
          if (typedRes.Success && !typedRes.Data) {
            callback(new Error("区域名称已存在"));
          } else if (!typedRes.Success) {
            callback(new Error("验证分区名称失败，请重试"));
          } else {
            callback();
          }
        } catch (error) {
          console.error(error);
          callback(new Error("验证分区名称失败，请重试"));
        }
      },
      trigger: "blur"
    }
  ]
});
